package com.aaa.member.controller;

import com.aaa.common.constants.ReturnCode;
import com.aaa.common.util.Result;
import com.aaa.member.entity.Client;
import com.aaa.member.entity.MemberLevel;
import com.aaa.member.service.ClientService;
import com.aaa.member.util.ExcelUtil;
import com.alibaba.fastjson.JSONObject;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * (Client)表控制层
 *
 * @author liduo
 * @since 2020-11-17 18:40:03
 */
@RestController
@RequestMapping("client")
@ApiOperation("客户信息控制类")
public class ClientController {
    /**
     * 服务对象
     */
    @Resource
    private ClientService clientService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Result selectOne(String id) {
        Integer clientId = Integer.valueOf(id);
        return this.clientService.queryById(clientId);
    }

    /**
     * 新增数据
     * 注册用户
     *
     * @param
     * @return 实例对象
     */
    @PostMapping("insert")
    public Result insert(@RequestBody String userName, String passWord, String verifyCode) {
        JSONObject json = (JSONObject) redisTemplate.opsForValue().get("yzm");
      /*  if (!json.get("verifyCode").equals(verifyCode)) {
            return new Result(ReturnCode.FAIL.getCode(), ReturnCode.FAIL.getMsg(), "验证码错误");
        }*/
       /* if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 5){
            return new Result(ReturnCode.FAIL.getCode(),ReturnCode.FAIL.getMsg(),"验证码过期");
        }*/
        if (redisTemplate.hasKey("yzm")) {
            return this.clientService.insert(userName, passWord);
        } else {
            return new Result(ReturnCode.FAIL.getCode(), ReturnCode.FAIL.getMsg(), "验证码过期");
        }


    }

    /**
     * 修改数据
     * 修改用户信息
     *
     * @param client 实例对象
     * @return 实例对象
     */
    @PutMapping("update")
    public Result update(@RequestBody Client client) {
        return this.clientService.update(client);
    }

    /**
     * 通过主键删除数据
     *
     * @param clientId 主键
     * @return 是否成功
     */
    @DeleteMapping("deleteById")
    public Result deleteById(Integer clientId) {
        return this.clientService.deleteById(clientId);


    }

    /**
     * 发送短信验证码
     * 阿里云接口
     *
     * @param phoneNum 接收的手机号
     */
    @GetMapping("sendSms")
    public Object sendSms(String phoneNum) {
        try {
            JSONObject json = null;
            //生成6位验证码
            String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
            System.out.println(verifyCode);
            //发送短信
            //设置超时时间-可自行调整
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            //初始化ascClient需要的几个参数
            final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
            final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
            //替换成你的AK
            final String accessKeyId = "LTAI4GGKhtUT2rmBRsyktcaU";//你的accessKeyId,参考本文档步骤2
            final String accessKeySecret = "8rvoXz3W5pevJhD51FVlmXyhXBN09l";//你的accessKeySecret，参考本文档步骤2
            //初始化ascClient,暂时不支持多region（请勿修改）
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                    accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            //使用post提交
            request.setMethod(MethodType.POST);
            //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
            request.setPhoneNumbers(phoneNum);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName("ABC商城");
            //必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
            request.setTemplateCode("SMS_205585024");
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
            request.setTemplateParam("{\"code\":\"" + verifyCode + "\"}");
            //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            //request.setOutId("yourOutId");
            //请求失败这里会抛ClientException异常
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if (redisTemplate.opsForValue().get("yzm") != null) {
                //如果redis存在则删除指定key
                redisTemplate.delete("yzm");
                //将验证码存到redis中,同时存入创建时间
                //以json存放，这里使用的是阿里的fastjson
                json = new JSONObject();
                json.put("verifyCode", verifyCode);
                json.put("createTime", System.currentTimeMillis());
                // 将认证码存入Redis
                redisTemplate.opsForValue().set("yzm", json, 10, TimeUnit.MINUTES);
            } else {
                //将验证码存到redis中,同时存入创建时间
                //以json存放，这里使用的是阿里的fastjson
                json = new JSONObject();
                json.put("verifyCode", verifyCode);
                json.put("createTime", System.currentTimeMillis());
                // 将认证码存入Redis
                redisTemplate.opsForValue().set("yzm", json, 10, TimeUnit.MINUTES);
            }
            if (sendSmsResponse.getMessage() != "OK") {
//
                return sendSmsResponse.getCode();
            } else {
                return "短信发送成功";
            }
            //榛子云短信接口代码
            /*ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "107195","NjUzMGFhZmUtN2U2MC00OGNmLWFjNmQtZjdkOThjMDJjNDcy");
            String result = client.send(phoneNum, "您的验证码为:" + verifyCode + "，该码有效期为5分钟，该码只能使用一次！【短信签名】");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("number", phoneNum);
            params.put("templateId", "2334");
            String[] templateParams = new String[2];
            templateParams[0] = verifyCode;
            templateParams[1] = "5分钟";
            params.put("templateParams", templateParams);
            String result = client.send(params);
             json = JSONObject.parseObject(result);
            if(json.getIntValue("code") != 0){//发送短信失败
                return json.getIntValue("code");}*/


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用户登录功能
     *
     * @param userNameOrPhoneNum
     * @param password
     */
    @GetMapping("Login")
    public Result userLogin(String userNameOrPhoneNum, String password) {
        return clientService.userLogin(userNameOrPhoneNum, password);
    }

    /**
     * 将client表导出到Excel表
     *
     * @return
     */

    @GetMapping("exportExcel")
    public String exportExcel(HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd hhmmss");
        String sheetName = "用户信息";
        // 初始化数据
        List<Client> clientList = clientService.ListClient();
        FileOutputStream out = null;
        //获取配置文件中保存对应excel文件的路径，本地也可以直接写成F：excel/testExcel
        String folderPath = ResourceBundle.getBundle("application").getString("downloadFolder") + File.separator + "testExcel";
        System.out.println(folderPath);
        //创建上传文件目录
        File folder = new File(folderPath);
        //如果文件夹不存在创建对应的文件夹
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //设置文件名
        String fileName = sdf1.format(new Date()) + sheetName + ".xls";
        // String savePath = folderPath + File.separator + fileName;
        response.setHeader("content-disposition",
                "attachment;fileName=" + fileName);
       /* try {


            out = new FileOutputStream(savePath);
            *//*out = new FileOutputStream(response.getOutputStream());*//*


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        ExcelUtil<Client> util = new ExcelUtil<Client>(Client.class); // 创建工具类.
        util.exportExcel(clientList, sheetName, 65536, response.getOutputStream()); // 导出
        System.out.println("----执行完毕----------");
        // System.out.println(savePath);
        //返回文件保存全路径
        return fileName;
    }

    @PostMapping("importExcel")
    public String importExcel(@RequestParam("file") MultipartFile file) {


        InputStream is = null;
        try {
            // @RequestParam("file") MultipartFile file 是用来接收前端传递过来的文件

            is = file.getInputStream();
            //下面是自己测试
            /*is = new FileInputStream("D:\\Poi测试\\会员测试.xls");*/

        } catch (IOException e) {
            e.printStackTrace();
        }
        ExcelUtil excelUtil = new ExcelUtil(Client.class);
        List list = excelUtil.importExcel("用户信息", is);
        int n = 0;
        for (int i = 0; i < list.size(); i++) {
            Client client = (Client) list.get(i);
            System.out.println(client);
            n = clientService.insertBy(client);
            System.out.println("i值为：" + list.get(i));
        }
        if (n > 0) {
            return "success";
        }
        return "失败";
    }
    /**
     * 根据手机号修改密码找回密码
     * 需要接收验证码
     */

    @PostMapping("updateByPhoneNum")
    public Result updateByPhoneNum(@RequestBody String PhoneNum ,String passWord, String verifyCode) {
        JSONObject json = (JSONObject) redisTemplate.opsForValue().get("yzm");
        if(!json.getString("verifyCode").equals(verifyCode)){
            return new Result(ReturnCode.FAIL.getCode(),ReturnCode.FAIL.getMsg(),"验证码错误");
        }
       /* if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 5){
            return new Result(ReturnCode.FAIL.getCode(),ReturnCode.FAIL.getMsg(),"验证码过期");
        }*/
        if (redisTemplate.hasKey("yzm")){
            return this.clientService.updateByPhoneNum(PhoneNum,passWord);
        }else {
            return new Result(ReturnCode.FAIL.getCode(),ReturnCode.FAIL.getMsg(),"验证码过期");
        }


    }

    /**
     * 查询指定行数据
     *
     * @param pageNo   查询起始位置
     * @param pageSize 查询条数
     * @param client
     * @return Result ---- Result.getData() 对象列表
     */
    @GetMapping("queryAllByParam")
    public Result queryAllByParam(Integer pageNo, Integer pageSize, Client client) {
        return this.clientService.queryAllByParam(pageNo, pageSize, client);
    }

}